package com.xt.website_manager.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: jiangyu
 * @Date: 2019/8/31 9:25
 * @Description:
 */
@Component
public class FileUploadUtil {

    /**
     * 按日期打散目录
     */
    public static File makeFullDirectoryObject(File storyDirectory) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateDirectory = sdf.format(new Date());
        //创建目录对象
        File file = new File(storyDirectory, dateDirectory);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 执行上传
     */
    public static void doUpload(MultipartFile[] proFile,String realPath) throws IOException {
        for (MultipartFile file : proFile) {
            if (file.isEmpty()) {
                //此文件域未进行上传
                System.out.println("请选择文件！");
            } else {
                //如果文件夹不存在，创建新的文件夹
                File upload_dir = new File(realPath);
                File directoryFile = makeFullDirectoryObject(upload_dir);
                // 把文件上传至path的路径，文件名改为为当前时间+原始文件名.扩展名
                File localFile = new File(directoryFile, UUID.randomUUID()+ file.getOriginalFilename());
                //执行上传
                file.transferTo(localFile);
            }
        }
    }

}
